<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 原始 list 如下
        let list = [
            { id: 1, name: '部门A', parentId: 0 },
            { id: 2, name: '部门B', parentId: 0 },
            { id: 3, name: '部门C', parentId: 1 },
            // { id: 4, name: '部门D', parentId: 1 },
            // { id: 5, name: '部门E', parentId: 2 },
            // { id: 6, name: '部门F', parentId: 3 },
            // { id: 7, name: '部门G', parentId: 2 },
            // { id: 8, name: '部门H', parentId: 4 }
        ];
        result(list)

        function result(departments) {
            const departmentMap = {};
            const rootDepartments = [];

            departments.forEach(item => {
                const { id, parentId } = item;
                item.children = [];
                departmentMap[id] = item;
                if (parentId === 0) {
                    rootDepartments.push(item);
                } else {
                    const parentDepartment = departmentMap[parentId];
                    console.log(departmentMap[parentId],'departmentMap[parentId]')
                    parentDepartment.children.push(item);
                }
            });
            // console.log(rootDepartments)
            return rootDepartments;
        }

    </script>
</body>

</html>